package com.mvc.framework.action;

import com.mvc.framework.entity.ActionFom;
import com.mvc.framework.entity.FillForm;
import com.mvc.framework.entity.XmlBean;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class ActionServlet extends javax.servlet.http.HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
		this.doGet(request, response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String path = this.getPath(request.getServletPath());
		Map<String, XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("strutsConfig");
		XmlBean xmlBean = map.get(path);
		if (xmlBean == null) {
			response.setStatus(404);
			return;
		}
		String formClass = xmlBean.getBeanClass();
		ActionFom form = FillForm.fill(formClass, request);
		String actionClazz = xmlBean.getActionClass();
		String url = "";

		try {
			Class clazz = Class.forName(actionClazz);
			IAction action = (IAction) clazz.newInstance();
			url = action.excute(request, form, xmlBean.getForward());
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("严重：控制器异常！");
		}

		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request, response);
	}

	private String getPath(String ServletPath) {
		if (ServletPath != null && !"".equals(ServletPath)) {
			return ServletPath.split("\\.")[0];
		}
		return "";
	}
}
